﻿import tkinter as tk

class Calculator:
    def __init__(self, root):
        self.root = root
        self.root.title("简易计算器")
        self.root.resizable(False, False)  # 禁止调整窗口大小
        
        # 创建显示区域
        self.display_var = tk.StringVar()
        self.display_var.set("0")
        display = tk.Entry(root, textvariable=self.display_var, font=('Arial', 20), 
                          justify='right', bd=10, bg='#f0f0f0', state='readonly')
        display.grid(row=0, column=0, columnspan=4, sticky='nsew', padx=5, pady=5)
        
        # 计算器按钮布局
        buttons = [
            ('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
            ('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
            ('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
            ('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
            ('C', 5, 0)
        ]
        
        # 创建按钮
        for (text, row, col) in buttons:
            if text == '=':
                btn = tk.Button(root, text=text, font=('Arial', 18), 
                               command=self.calculate, bg='#4CAF50', fg='white')
            elif text == 'C':
                btn = tk.Button(root, text=text, font=('Arial', 18), 
                               command=self.clear, bg='#f44336', fg='white')
            else:
                btn = tk.Button(root, text=text, font=('Arial', 18), 
                               command=lambda t=text: self.append(t))
            
            btn.grid(row=row, column=col, sticky='nsew', padx=2, pady=2)
            btn.config(height=2, width=4)
        
        # 配置网格权重
        for i in range(6):
            root.grid_rowconfigure(i, weight=1)
        for i in range(4):
            root.grid_columnconfigure(i, weight=1)
        
        self.expression = ""
        self.is_calculated = False

    def append(self, char):
        if self.is_calculated and char not in '+-*/':
            self.clear()
            self.is_calculated = False
            
        if self.display_var.get() == "0" and char != '.':
            self.expression = char
        else:
            self.expression += char
            
        self.display_var.set(self.expression)

    def clear(self):
        self.expression = ""
        self.display_var.set("0")

    def calculate(self):
        try:
            result = eval(self.expression)
            self.display_var.set(str(result))
            self.expression = str(result)
            self.is_calculated = True
        except:
            self.display_var.set("错误")
            self.expression = ""

if __name__ == "__main__":
    root = tk.Tk()
    calc = Calculator(root)
    root.mainloop()


